package io.babystar.modules.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.babystar.common.exception.RRException;
import io.babystar.common.utils.PageUtils;
import io.babystar.common.utils.R;
import io.babystar.common.utils.ShiroUtils;
import io.babystar.modules.business.entity.*;
import io.babystar.modules.business.service.*;
import io.babystar.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("business/cwOrder")
public class CWOrderController {
    @Autowired
    private CWOrderService cwOrderService;
    @Autowired
    private CWCategoryService cwCategoryService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private CwFinancialDetailsService cwFinancialDetailsService;
    @Autowired
    private PartnerTypeService partnerTypeService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("business:cwOrder:list")
    public R list(@RequestParam Map<String, Object> params){
        SysUserEntity userEntity = (SysUserEntity) ShiroUtils.getSubject().getPrincipal();
        params.put("businessId",userEntity.getBusinessId());
        int type = userEntity.getType();
        if(type==2 || type==3){
            long teacherId = userEntity.getParentTeacherId();
            TeacherEntity teacherEntity = teacherService.getById(teacherId);
            params.put("shopId",teacherEntity.getShopId().toString());
        }
        PageUtils page = cwOrderService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @RequiresPermissions("business:cwOrder:info")
    public R info(@PathVariable("id") Long id){
        CWOrderEntity cwOrder = cwOrderService.getById(id);
        if(null != cwOrder){
            cwOrder.setCategoryName(cwCategoryService.getById(cwOrder.getCategoryId()).getCategory());
            //cwOrder.setStudentName(studentService.getById(cwOrder.getStudentId()).getStudentName());
            //获取配合人id
            List<CwFinancialDetailsEntity> list = cwFinancialDetailsService.list(new QueryWrapper<CwFinancialDetailsEntity>().eq("order_id", cwOrder.getId()));
            list.forEach(e -> {
                if(e.getType() == 1){
                    cwOrder.setYaoyueId(e.getTeacherId());
                }else if(e.getType() == 2){
                    cwOrder.setTiyanId(e.getTeacherId());
                }else if(e.getType() == 3){
                    cwOrder.setGenjinId(e.getTeacherId());
                }
            });
        }
        return R.ok().put("cwOrder", cwOrder);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("business:cwOrder:save")
    @Transactional
    public R save(@RequestBody CWOrderEntity cwOrder){
        SysUserEntity userEntity = (SysUserEntity) ShiroUtils.getSubject().getPrincipal();
        int type = userEntity.getType();
        //1:机构总帐号 2:店长
        if(type==1){

        }else if(type==2){
            TeacherEntity teacherEntity = teacherService.getById(userEntity.getParentTeacherId());
            cwOrder.setShopId(teacherEntity.getShopId());
        }else {
            return R.error("当前账号没有权限 type=" + type);
        }
        cwOrder.setCreator(userEntity.getUserId().toString());
        cwOrder.setCreateAt(new Date());
        cwOrder.setBusinessId(Integer.parseInt(userEntity.getBusinessId()+""));
        TeacherEntity yaoYue = teacherService.getById(cwOrder.getYaoyueId());
        if(null != yaoYue){
            cwOrder.setYaoyue(yaoYue.getTeacherName());
        }
        TeacherEntity tiYan = teacherService.getById(cwOrder.getTiyanId());
        if(null != tiYan){
            cwOrder.setTiyan(tiYan.getTeacherName());
        }
        TeacherEntity genJin = teacherService.getById(cwOrder.getGenjinId());
        if(null != genJin){
            cwOrder.setGenjin(genJin.getTeacherName());
        }
        cwOrderService.save(cwOrder);

        //邀约、体验、跟进分成三条记录保存到财务明细表
        CwFinancialDetailsEntity cwFinancialDetailsEntity = new CwFinancialDetailsEntity();
        cwFinancialDetailsEntity.setOrderId(cwOrder.getId());
        cwFinancialDetailsEntity.setCreator(userEntity.getUserId().toString());
        cwFinancialDetailsEntity.setCreateAt(new Date());
        if(StringUtils.isNotBlank(cwOrder.getYaoyue())){
            String moneyProportion = this.getMoneyProportion(userEntity.getBusinessId(), cwOrder.getShopId(), 1);
            if(StringUtils.isEmpty(moneyProportion)){
                throw new RRException("请先配置分红比例");
            }
            cwFinancialDetailsEntity.setMoney(cwOrder.getOrderAmount().multiply(new BigDecimal(moneyProportion)));
            cwFinancialDetailsEntity.setTeacherName(cwOrder.getYaoyue());
            cwFinancialDetailsEntity.setTeacherId(cwOrder.getYaoyueId());
            cwFinancialDetailsEntity.setType(1);
            cwFinancialDetailsService.save(cwFinancialDetailsEntity);
        }
        if(StringUtils.isNotBlank(cwOrder.getTiyan())){
            String moneyProportion = this.getMoneyProportion(userEntity.getBusinessId(), cwOrder.getShopId(), 2);
            if(StringUtils.isEmpty(moneyProportion)){
                throw new RRException("请先配置分红比例");
            }
            cwFinancialDetailsEntity.setMoney(cwOrder.getOrderAmount().multiply(new BigDecimal(moneyProportion)));
            cwFinancialDetailsEntity.setTeacherName(cwOrder.getTiyan());
            cwFinancialDetailsEntity.setTeacherId(cwOrder.getTiyanId());
            cwFinancialDetailsEntity.setType(2);
            cwFinancialDetailsService.save(cwFinancialDetailsEntity);
        }
        if(StringUtils.isNotBlank(cwOrder.getGenjin())){
            String moneyProportion = this.getMoneyProportion(userEntity.getBusinessId(), cwOrder.getShopId(), 3);
            if(StringUtils.isEmpty(moneyProportion)){
                throw new RRException("请先配置分红比例");
            }
            cwFinancialDetailsEntity.setMoney(cwOrder.getOrderAmount().multiply(new BigDecimal(moneyProportion)));
            cwFinancialDetailsEntity.setTeacherName(cwOrder.getGenjin());
            cwFinancialDetailsEntity.setTeacherId(cwOrder.getGenjinId());
            cwFinancialDetailsEntity.setType(3);
            cwFinancialDetailsService.save(cwFinancialDetailsEntity);
        }

        return R.ok();
    }

    public String getMoneyProportion(Long businessId,Integer shopId,Integer partner) {
        PartnerTypeEntity partnerEntity = partnerTypeService.getOne(new QueryWrapper<PartnerTypeEntity>()
                .eq("business_id", businessId)
                .eq("shop_id", shopId)
                .eq("partner", partner));
        if(null != partnerEntity){
            String moneyProportion = partnerEntity.getMoneyProportion();
            String replace = moneyProportion.replace("%", "");
            Float f = Float.valueOf(replace) / 100;
            return f.toString();
        }
        return null;
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("business:cwOrder:update")
    public R update(@RequestBody CWOrderEntity cwOrder){
        SysUserEntity userEntity = (SysUserEntity) ShiroUtils.getSubject().getPrincipal();
        int type = userEntity.getType();
        //1:机构总帐号 2:店长
        if(type==1){
            //todo
        }else if(type==2){
            TeacherEntity teacherEntity = teacherService.getById(userEntity.getParentTeacherId());
            cwOrder.setShopId(teacherEntity.getShopId());
        }else{
            return R.error("当前账号没有权限");
        }
        cwOrder.setUpdator(userEntity.getUserId().toString());
        cwOrder.setUpdateAt(new Date());
        cwOrder.setBusinessId(Integer.parseInt(userEntity.getBusinessId()+""));
        cwOrderService.updateById(cwOrder);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("business:cwOrder:delete")
    public R delete(@RequestBody Long[] ids){
        cwOrderService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 退费管理-获取订单
     */
    @RequestMapping("/getOrderList")
    public R getOrderList() {
        List<CWOrderEntity> list = cwOrderService.list();
        return R.ok().put("list", list);
    }

}
